<?php

namespace app\common\service\deploy;

use app\admin\model\order\Order as OrderModel;
use app\admin\model\user\User as UserModel;
use app\common\service\BaseService;
use app\common\service\OrderService;

class RechargeService extends BaseService
{
    /**
     * 处理用户充值订单
     */
    public static function pay($params)
    {
        //充值订单编号
        $params['order_no'] = OrderService::createOrderNo('Rege');
        $params ['is_recharge'] = 1;
        //查询用户原来余额
        $userMoney = UserModel::where('id', $params['user_id'])->value('money');
        $money = $params['price'] + $params['give'] + $userMoney;
        self::beginTrans();
        try {
            $params['pay_price'] = $params['price'] + $params['give'];
            $orderRes = OrderModel::create($params);
            $orderRes && $orderRes = $orderRes->toArray();
            $userRes = UserModel::where('id', $params['user_id'])->update(['money' => $money]);
            if ($orderRes && $userRes) {
                return self::success('充值成功', ['order' => $orderRes, 'userMoney' => $params['price'] + $params['give']]);
            }
            self::commitTrans();
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::fail('充值失败');
        }
    }
}